<template>
    <div>
        <f7-block strong inset style="margin-top:5px; margin-bottom:5px;">
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>实测点数</span>
                </f7-col>
                <f7-col width="70">
                    <f7-stepper fill :value="form.measurePoints" :step="1" :min="0" :max="1000"
                        :autorepeat="true" :wraps="true" :manual-input-mode="true"
                        @stepper:change="pointCountChange()">
                    </f7-stepper>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom: 5px;">
                <f7-col width="30">
                    <span>爆点数值</span>
                    <f7-link @click="addProblemValue" v-if="houseType == null || houseType.url == null">
                        <f7-icon f7="add_round"></f7-icon>
                    </f7-link>
                </f7-col>
                <f7-col width="70" v-if="houseType && houseType.url">
                    <f7-button @click="openHousePoint">在户型图上标记</f7-button>
                    <f7-row style="margin-top:10px; margin-bottom:10px;"
                        v-for="(value, i) in form.problemValues" v-if="i % 5 == 0" :key="i">
                        <f7-col v-for="j in 5" :key="i + '-' + j">
                            <span>{{(i + j - 1 < form.problemValues.length) ? form.problemValues[i + j - 1].val: ''}}</span>
                        </f7-col>
                    </f7-row>
                </f7-col>
                <f7-col width="70" v-else>
                    <f7-row style="margin-top:10px; margin-bottom:10px;"
			            v-for="(value, i) in form.problemValues" v-if="i % 3 == 0" :key="i">
			            <f7-col v-for="j in 3" :key="i + '-' + j">
			                <f7-button v-if="i + j - 1 < form.problemValues.length" 
			                    @click="pointClick(i + j - 1)"
			                    :id="'value-image-btn-' + (i + j - 1)">
			                    {{form.problemValues[i + j - 1].val}}
			                </f7-button>
			                <PopoverKeyboard :ref="'popoverKeyboard-' + (i + j - 1)" 
			                    :index="i + j - 1" :count="form.problemValues.length"
			                    @delete="pointDelete(i + j - 1)"
			                    @next="nextPointClick(i + j - 1)"
			                    @change="pointChange(i + j - 1, $event)">
			                </PopoverKeyboard>
			            </f7-col>
			        </f7-row>
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <f7-col width="30">
                    <span>合格率</span>
                </f7-col>
                <f7-col width="30">
                    <span>{{qualificationRate}}%</span>
                </f7-col>
                <f7-col width="40">
                    <f7-checkbox :checked="form.repair != null" @change="toggleRepair"></f7-checkbox>&nbsp;&nbsp;通知整改
                </f7-col>
            </f7-row>
            <f7-row style="margin-bottom:5px;">
                <TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
            </f7-row>
            <f7-list inline-labels no-hairlines style="margin-top:5px; margin-bottom:5px;">
                <f7-list-item v-show="form.repair != null" id="repairUserSmartSelect" smart-select
	                :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
	                <f7-label>整改人</f7-label>
	                <select v-model="form.repair">
	                    <optgroup label="施工单位">
	                        <option v-for="(userId, i) in contractors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                    <optgroup label="监理单位">
	                        <option v-for="(userId, i) in supervisors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                    <optgroup label="建设单位">
	                        <option v-for="(userId, i) in constructors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                </select>
	            </f7-list-item>
	            <f7-list-item id="ccUserSmartSelect" smart-select
	                :smart-select-params="{openIn: 'popup', searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
	                <f7-label>抄送人</f7-label>
	                <select multiple v-model="form.ccs">
	                    <optgroup label="施工单位">
	                        <option v-for="(userId, i) in contractors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                    <optgroup label="监理单位">
	                        <option v-for="(userId, i) in supervisors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                    <optgroup label="建设单位">
	                        <option v-for="(userId, i) in constructors" :key="userId"
	                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
	                        </option>
	                    </optgroup>
	                </select>
	            </f7-list-item>
	            <f7-list-item>
	                <f7-list-button title="暂存" style="width:100%;" @click="saveTemporary">
	                </f7-list-button>
	                <f7-list-button title="提交" style="width:100%;" @click="submit" v-show="isOnline">
	                </f7-list-button>
	            </f7-list-item>
            </f7-list>
        </f7-block>
    </div>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import userCategory from '@/mixins/userCategory.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import $ from 'jquery';
import events from 'events';
import store from '@/store';
import request from '@/utils/request';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { upload, uploadImage } from '@/utils/upload';
import TakePhoto from "@/components/TakePhoto.vue";
import PopoverKeyboard from "@/components/PopoverKeyboard.vue";

export default {
    store: store,
    mixins: [networkEvent, back, userCategory],
    components: {
        TakePhoto,
        PopoverKeyboard
    },
    props: {
    	houseId: {
    		type: String
    	},
    	itemId: {
    		type: String
    	},
    	appPermission: {
    		type: String
    	},
    	unitId: {
    		type: String
    	},
    	floorId: {
    		type: String
    	}
    },
    data: function() {
        return {
        	isOnline: true,
        	stepper: null,
        	houseType: null,
        	defaultRepair: null,
        	form: {
        		tid: null,
        		buildingId: null,
        		unitId: null,
        		floorId: null,
        		houseId: null,
        		itemId: null,
        		measurePoints: 0,
        		problemValues: [],
        		regist: getUser().userId,
        		repair: null,
        		ccs: [],
        		photos: [],
        		appPermission: null
        	},
        	deletePhotos: []
        };
    },
    methods: {
        pointCountChange: function() {
            this.form.measurePoints = this.stepper.getValue();
        },
        openHousePoint: function() {
        	var self = this;
        	var router = this.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: this.houseType.url,
                    pointCount: this.form.measurePoints,
                    initialPoints: this.form.problemValues,
                    overPointCountMessage: '爆点数不能超过测量点数',
                    hasPointValue: true
                }
            });
            router.off('pointAdd');
            router.on('pointAdd', function(point) {
                self.form.problemValues.push(point);
            });
            router.off('pointDelete');
            router.on('pointDelete', function(point) {
                for(var i = 0; i < self.form.problemValues.length; i++) {
                    if(point.x == self.form.problemValues[i].x
                        && point.y == self.form.problemValues[i].y) {
                        self.form.problemValues.splice(i, 1);
                        break;
                    }
                }
            });
            router.off('pointChange');
            router.on('pointChange', function(point) {
                for(var i = 0; i < self.form.problemValues.length; i++) {
                    if(point.x == self.form.problemValues[i].x
                        && point.y == self.form.problemValues[i].y) {
                        self.form.problemValues.splice(i, 1, point);
                        break;
                    }
                }
            });
        },
        addProblemValue: function() {
        	if(this.form.problemValues.length >= this.form.measurePoints) {
        		this.$f7.dialog.alert('', '爆点数不能超过实测点数');
        		return;
        	}
        	var problemValue = {
        		val: null
        	}
        	this.form.problemValues.push(problemValue);
        },
        pointClick: function(index) {
        	this.$refs['popoverKeyboard-' + index][0].open('#value-image-btn-' + index);
        },
        pointDelete: function(index) {
        	this.form.problemValues.splice(index, 1);
        },
        nextPointClick: function(index) {
            this.$refs['popoverKeyboard-' + index][0].close();
            this.pointClick(index + 1);
        },
        pointChange: function(index, value) {
        	this.form.problemValues[index].val = value;
        },
        toggleRepair: function() {
        	if(this.form.repair != null) {
        		this.form.repair = null;
        	} else {
        		if(this.defaultRepair == null) {
        			this.form.repair = '';
                    this.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue('');
        		} else {
        			this.form.repair = this.defaultRepair;
                    this.$f7.smartSelect.get('#repairUserSmartSelect .smart-select')
                        .setValue(this.$store.state.global.userMap[this.form.repair].realname);
        		}
        	}
        },
        photoAdd: function(cdvPath) {
            this.form.photos.push(cdvPath);
        },
        photoDelete: function(cdvPath) {
            for(var i = 0; i < this.form.photos.length; i++) {
                if(cdvPath == this.form.photos[i]) {
                	this.form.photos.splice(i, 1);
                    if(cdvPath.indexOf('qualityMeasure') > -1) {
                        this.deletePhotos.push(cdvPath);
                    }
                    break;
                }
            }
        },
        saveTemporary: function() {
            var self = this;
            self.$f7.preloader.show();
            let promises = [];
            self.deletePhotos.forEach(photo => {
    	        let promise = FileUtil.remove(photo).then(() => {
    	        	return Promise.resolve();
    	        }).catch((error) => {
    	        	console.error(error);
    	        	return Promise.resolve();
    	        });
    	        promises.push(promise);
    		});
            Promise.all(promises).then(() => {
    			let promises = [];
    			self.form.photos.forEach(photo => {
    				let promise = null;
    				if(photo.indexOf(Common.directory().qualityMeasure) < 0) {
    					let splits = photo.split('/');
    					let filename = splits[splits.length - 1];
    					let to = Common.directory().base + Common.directory().qualityMeasure + filename;
    					promise = FileUtil.copy(photo, to);
    				} else {
    					promise = new Promise((resolve, reject) => {
    						resolve(photo);
    					});
    				}
                    promises.push(promise);
    			});
    			return Promise.all(promises);
    		}).then((paths) => {
    			let photos = [];
    			paths.forEach(path => {
    				photos.push(path);
    			});
    			self.form.photos = photos;
    			self.form.place = self.place;
    			let sql = '';
    			if(self.form.tid == null) {
    				sql = "\
    	                insert into tmp_quality_measure_checkquality_problem_regist( \
    	                building_id, unit_id, floor_id, house_id, item_id, \
    	                repair, ccs, photos, measure_points, problem_values, app_permission) \
    	                values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) \
    	            "; 
    			} else {
    				sql = "\
    	                update tmp_quality_measure_checkquality_problem_regist \
    	                set building_id = ?, unit_id = ?, floor_id = ?, house_id = ?, \
    	                item_id = ?, repair = ?, ccs = ?, photos = ?, measure_points = ?, problem_values = ?, \
    	                app_permission = ? \
    	                where tid = '" + self.form.tid + "' \
    	            ";
    			}
    			var values = [
    				self.form.buildingId,
    				self.form.unitId,
    				self.form.floorId,
    				self.form.houseId,
    				self.form.itemId,
    				self.form.repair,
    	            JSON.stringify(self.form.ccs),
    	            JSON.stringify(self.form.photos),
    	            self.form.measurePoints,
    	            JSON.stringify(self.form.problemValues),
    	            self.form.appPermission
    	        ];
    			return Common.executeSql(sql, values);
    		}).then((result) => {
    			let tid = self.form.tid == null ? result.rs.insertId : self.form.tid
    			let promises = [];
            	let promise = null;
           		let sql = " \
            	    select * from tmp_quality_measure_checkquality_problem_regist \
            	    where tid = '" + tid + "' \
            	";
           		promise = Common.executeSql(sql, []).then((result) => {
           			let rs = result.rs;
           			let row = rs.rows.item(0);
                    let checkItemGuideline = self.$store.state.global.checkItemGuidelineMap[row.item_id];
                    let key = row.house_id;
                    if(checkItemGuideline) {
                    	if(checkItemGuideline.process_mode != '1') {
                    		key = row.unit_id + '_' + row.floor_id;
                    	}
                    }
            		self.$set(self.$store.state.global.draftMap, key, row);
    	        	return Promise.resolve();
    	        }).catch((error) => {
    	        	return Promise.reject(error);
    	        });;
           		promises.push(promise);
            	return Promise.all(promises);
            	
    		}).then(() => {
    			self.$f7.dialog.alert('', '暂存问题成功');
    			self.$f7router.emit('saveTemporary', self.form.tid);
                self.$f7.preloader.hide();
                self.$f7router.back();
    		}).catch(error => {
    			console.error(error);
    			self.$f7.dialog.alert('', '暂存问题失败');
    			self.$f7.preloader.hide();
    		});
        },
        submit: function() {
            var self = this;
            if(!Common.isOnline()) {
    			this.$f7.dialog.alert('', '当前网络信号较弱，问题已暂存到手机!');
    			this.saveTemporary();
    			return;
    		}
            if(this.form.repair == '') {
            	this.$f7.dialog.alert('', '请选择整改人');
            }
            this.$f7.dialog.confirm('', '确定提交吗?', function() {
                /* self.$f7.preloader.show(); */
                let dialog = self.$f7.dialog.progress('上传图片中', 0);
                dialog.finishCount = 0;
                let data = {
               		appPermission: self.form.appPermission,
                    buildingId: self.form.buildingId,
                    unitId: self.form.unitId,
                    floorId: self.form.floorId,
                    houseId: self.form.houseId,
                    itemId: self.form.itemId,
                    measurePoints: self.form.measurePoints,
                    regist: self.form.regist,
                    values: [],
                    pointsX: [],
                    pointsY: [],
                    photos: [],
                    deletePhotos: [],
                    ccs: []
                };
                self.form.problemValues.forEach(function(problemValue) {
                    data.values.push(problemValue.val);
                    if(self.houseType && self.houseType.url) {
                        data.pointsX.push(problemValue.x);
                        data.pointsY.push(problemValue.y);
                    }
                });
                /* for(var i = 0; i < self.form.photos.length; i++) {
                    data.photos.push(self.form.photos[i]);
                } */
                for(var i = 0; i < self.deletePhotos.length; i++) {
                    data.deletePhotos.push(self.deletePhotos[i]);
                }
                if(self.form.repair != null) {
                    data.repair = self.form.repair;
                }
                self.form.ccs.forEach(function(cc) {
                    data.ccs.push(cc);
                });
                let promises = [];
                self.form.photos.forEach(photoPath => {
                	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
                		let splits = photoPath.split("/");
                		let filename = splits[splits.length - 1];
                		return uploadImage(filename, blob);
                	}).then(result => {
                		data.photos.push({url: result.url});
                		dialog.finishCount++;
                		dialog.setProgress(parseInt(dialog.finishCount / (self.form.photos.length + 1)) * 100);
                		return Promise.resolve();
                	});
                	promises.push(promise);
                });
                /* for(var i = 0; i < self.form.photos.length; i++) {
                    (function(index) {
                        let filePath = self.form.photos[index];
                        let promise = FileUtil.read(filePath, 'image/jpeg');
                        promises.push(promise);
                    })(i);
                } */
                Promise.all(promises).then((blobs) => {
                	/* blobs.forEach(blob => {
                		data.photos.push(blob);
                	}); */
                	return request({
                		url: '/rest/api/v3/qualityMeasureCheckQualityProblem/add',
                		method: 'post',
                		data: data
                	});
                }).then(data => {
                	let element = data.element;
                	let promises = [];
                	let promise = null;
                	if(self.form.tid != null) {
                		let sql = "\
                	        delete from tmp_quality_measure_checkquality_problem_regist \
                	        where tid = '" + self.form.tid + "' \
                		";
                		promise = Common.executeSql(sql, []);
                		promises.push(promise);
                	}
                	self.$emit('submitedProblem', element);
                	return Promise.all(promises);
                }).then(() => {
                	dialog.close();
                	self.$f7.dialog.alert('', '提交问题成功！');
                    /* self.$f7.preloader.hide(); */
                    self.$f7router.back();
                }).catch(error => {
                	dialog.close();
                	console.error(error);
                	self.$f7.dialog.alert('', '提交失败，问题已暂存到手机！');
                	self.saveTemporary();
                	/* self.$f7.preloader.hide(); */
                	self.$f7router.back();
                });
                var checkItemGuideline = self.$store.state.global.checkItemGuidelineMap[self.itemId];
                var key = self.houseId;
                if(checkItemGuideline) {
                    if(checkItemGuideline.process_mode != '1') {
                        key = self.unitId + '_' + self.floorId;
                    }
                }
                self.$set(self.$store.state.global.draftMap, key, null);
                
            });
        },
        houseIdChanged: function(newVal, oldVal) {
            if(this.houseId == null) {
                this.houseType = null;
                this.form.houseId = null;
            } else {
                var house = this.$store.state.global.houseMap[this.houseId];
                if(house.house_type_id != null) {
                    this.houseType = this.$store.state.global.houseTypeMap[house.house_type_id];
                } else {
                    this.houseType = null;
                }
                var unit = this.$store.state.global.unitMap[house.unit_id];
                var floor = this.$store.state.global.floorMap[house.floor_id];
                var building = this.$store.state.global.buildingMap[unit.building_id];
                this.form.houseId = house.id;
                this.form.unitId = unit.id;
                this.form.floorId = floor.id;
                this.form.buildingId = building.id;
            }
            
        },
        itemIdChanged: function(newVal, oldVal) {
            var self = this;
            var checkItemGuideline = this.$store.state.global.checkItemGuidelineMap[this.itemId];
            if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
                var house = this.$store.state.global.houseMap[this.houseId];
                var unit = this.$store.state.global.unitMap[house.unit_id];
            } else {
            	var unit = this.$store.state.global.unitMap[this.unitId];
            }
            var building = this.$store.state.global.buildingMap[unit.building_id];
            var bidSection = this.$store.state.global.bidSectionMap[building.bid_section_id];
            var problemClassIds = this.$store.state.global.bidSectionCheckItemRel.bidSectionMap[bidSection.id];
            for(var itemId in problemClassIds){
                var bidSectionCheckItem = this.$store.state.global.bidSectionCheckItemRel[problemClassIds[itemId]];
                if(bidSectionCheckItem.bid_section_id == bidSection.bid_section_id &&
                    bidSectionCheckItem.check_item_id == this.itemId) {
                    this.defaultRepair = bidSectionCheckItem.repair;
                    if(this.form.ccs.length == 0) {
                        this.form.ccs = (bidSectionCheckItem.cc == null || bidSectionCheckItem.cc == '')
                            ? [] : bidSectionCheckItem.cc.split(',');
                        this.$f7.smartSelect.get('#ccUserSmartSelect .smart-select')
                            .setValue(this.form.ccs.map(function(cc) {
                                return self.$store.state.global.userMap[cc].realname;
                            }).join(',')
                        );
                    }
                    break;
                }
            }
            this.form.itemId = this.itemId;
        }
    },
    computed: {
    	qualificationRate: function() {
    		if(this.form.measurePoints == 0) {
    			return 0;
    		}
    		var rate = 1 - this.form.problemValues.length / this.form.measurePoints;
    		return (rate * 100).toFixed(1);
    	}
    },
    watch: {
        'form.measurePoints': function(newVal, oldVal) {
            this.stepper.setValue(this.form.measurePoints);
            while(this.form.problemValues.length > this.form.measurePoints) {
                this.form.problemValues.pop();
            }
        },
        'houseId': function(newVal, oldVal) {
        	this.houseIdChanged(newVal, oldVal);
        },
        'itemId': function(newVal, oldVal) {
        	this.itemIdChanged(newVal, oldVal);
        }
    },
    created: function() {
    	
    },
    mounted: function() {
        this.isOnline = Common.isOnline();
        var self = this;
        
        self.$f7.preloader.show();
        var checkItemGuideline = this.$store.state.global.checkItemGuidelineMap[this.itemId];
        if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
            self.houseIdChanged(self.houseId, null);
        } else {
        	self.form.floorId = self.floorId;
        	self.form.unitId = self.unitId;
        	var floor = self.$store.state.global.floorMap[self.floorId];
        	self.form.buildingId = floor.building_id;
        }
        self.itemIdChanged(self.itemId, null);
        self.stepper = self.$f7.stepper.get('.stepper');
        this.form.appPermission = this.appPermission;
        let sql = "\
    	    select * \
    	    from tmp_quality_measure_checkquality_problem_regist \
    	    where item_id = '" + self.itemId + "' \
    	    and app_permission = '" + self.appPermission + "' \
    	    and floor_id = '" + self.floorId + "' \
            and unit_id = '" + self.unitId + "' \
    	";
    	if(checkItemGuideline == null || checkItemGuideline.process_mode == '1') {
    		sql += "\
    		    and house_id = '" + self.houseId + "' \
    		";
    	}
    	Common.executeSql(sql, []).then((result) => {
    		let rs = result.rs;
    		if(rs.rows.length > 0) {
    			var row = rs.rows.item(0);
    			self.form.tid = row.tid;
    			self.form.measurePoints = row.measure_points;
    			self.form.problemValues = Common.strToJson(row.problem_values);
    			self.form.photos = Common.strToJson(row.photos);
    			self.$refs['refTakePhoto'].addPhotos(self.form.photos);
    			self.form.repair = row.repair;
    			self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select')
    			    .setValue(self.$store.state.global.userMap[self.form.repair].realname);
    			self.form.ccs = Common.strToJson(row.ccs);
                self.$f7.smartSelect.get('#ccUserSmartSelect .smart-select')
                    .setValue(self.form.ccs.map(function(cc) {
                        return self.$store.state.global.userMap[cc].realname;
                    }).join(',')
                );
    		}
    		this.$f7.preloader.hide();
    	}).catch(error => {
			console.error(error);
			this.$f7.preloader.hide();
		});
        
    }
}
</script>

<style scoped>

</style>